package vboot.core.security.authc;

import cn.hutool.core.util.IdUtil;
import vboot.core.common.api.R;
import vboot.core.common.dao.JdbcDao;
import vboot.core.config.AppConfig;
import vboot.core.config.dbx.ldap.LdapHandler;
import vboot.core.config.dbx.redis.RedisHandler;
import vboot.core.security.authz.JwtHandler;
import vboot.core.security.pojo.*;
import vboot.core.module.mon.log.login.MonLogLoginService;
import vboot.core.module.sys.org.user.SysOrgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.security.core.Authentication;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import vboot.core.xutil.lang.XstrUtil;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController
public class AuthcApi {

    @PostMapping("/login")
    public R login(@Valid @RequestBody LoginVo loginVo, HttpServletRequest request) throws IOException, ClassNotFoundException {
//        System.out.println("开始登录");
        //1.登录验证
        UserDo userDo = null;
        try {
            userDo = jdbcDao.getTp().queryForObject("select id,name,pacod,retag from sys_org_user where usnam=? and avtag=1",
                    new Object[]{loginVo.getUsername()}, new BeanPropertyRowMapper<>(UserDo.class));
        } catch (DataAccessException ignored) {

        }

        boolean passFlag = false;
        if (userDo != null) {
            String encodePassword = DigestUtils.md5DigestAsHex(("abc" + loginVo.getPassword() + "xyz").getBytes());//数据库密码验证
            if (encodePassword.equals(userDo.getPacod())) {
                passFlag = true;
            } else {
                //passFlag = ldapHandler.authenticate(loginVo.getUsername(), loginVo.getPassword());//AD域密码验证
            }
        }
        if (!passFlag) {
            return R.build(402, "账号不存在或密码错误");
        }

        //2.初始化用户信息，获取菜单与权限
        String atokenUUID = IdUtil.simpleUUID();
        String atoken = jwtHandler.createTokenByUuid(atokenUUID);
        String rtoken = jwtHandler.createTokenByUuid(loginVo.getUsername());//需要加密下

        Map<String, Object> backMap = new HashMap<>();
        backMap.put("token", atoken);
        backMap.put("rtoken", rtoken);

        Zuser zuser = new Zuser(userDo.getId(), userDo.getName(), loginVo.getUsername());
        authcService.initZuser(zuser, userDo, backMap);//初始化用户


        redisHandler.set("online-key:"+atokenUUID, zuser, appConfig.getJwt().getAtime());//默认8小时过期

        //3.异步方式记录登录日志
        monLogLoginService.save("online-key:"+atokenUUID,zuser,request);
        return R.ok(backMap);

    }

    @GetMapping("/rtoken")
    public R rtoken(@PathParam("token2") String token2) {
        System.out.println("token2=" + token2);
        String username = jwtHandler.getClaims(token2).getId();
        System.out.println("username=" + username);
        String uuid = IdUtil.simpleUUID();
        String token = jwtHandler.createTokenByUuid(uuid);
        Zuser zuser = authcService.getUser(username);
        redisHandler.set(uuid, zuser, 10000 / 1000);
        Map<String, Object> backMap = new HashMap<>();
        backMap.put("token", token);
        return R.ok(backMap);
    }

    @GetMapping("/logout")
    public R logout(Authentication auth) {
        return R.ok();
    }

    @GetMapping("/getUserInfo")
    public R getUserInfo(Authentication auth, HttpServletRequest request) {
        Zuser zuser = (Zuser) auth.getPrincipal();
        //monLogLoginService.save(zuser,request);
        return R.ok(zuser);
    }

    @GetMapping("/getMenuList")
    public R getMenuList(String porid, Authentication auth, HttpServletRequest request) {
        if(auth==null){
            //System.out.println("登录过期");
            return R.build(401,"登录过期");
        }
        Map<String, Object> backMap = new HashMap<>();
        Zuser zuser = (Zuser) auth.getPrincipal();

        UserDo userDo  = jdbcDao.getTp().queryForObject("select id,name,pacod,retag from sys_org_user where id=? and avtag=1",
                    new Object[]{zuser.getId()}, new BeanPropertyRowMapper<>(UserDo.class));
        if(XstrUtil.isBlank(porid)){
            authcService.initZuser(zuser, userDo, backMap);
        }else{
            authcService.initZuser2(zuser, backMap,porid);
        }
//        monLogLoginService.save(zuser,request);

        return R.ok(backMap);
    }


    @Autowired
    private AuthcService authcService;

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private RedisHandler redisHandler;

    @Autowired
    private JwtHandler jwtHandler;

    @Autowired
    private LdapHandler ldapHandler;

    @Autowired
    private JdbcDao jdbcDao;

    @Autowired
    private MonLogLoginService monLogLoginService;

    @Autowired
    private SysOrgUserService userService;


}
